import echarts from "echarts";
import zrender from "zrender";
import { addCircleToChart, animateRotate } from "./base";
import { toRad } from "../utils";

const elements = {};

function draw(chart, percentage) {
  let gradient = new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
    { offset: 0, color: "rgba(0, 0, 0, 0)" },
    { offset: 1, color: "rgba(0, 138, 175, 0.5)" }
  ]);

  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;

  let arcOpts = [
    {
      startAngle: 10,
      endAngle: 170,
      reverse: false
    },
    {
      startAngle: 190,
      endAngle: 350,
      reverse: false
    },
  ];

  arcOpts.forEach(arcOpt => {
    let arc = new zrender.Arc({
      origin: [cx, cy],
      shape: {
        cx: cx,
        cy: cy,
        r: 60,
        startAngle: toRad(arcOpt.startAngle),
        endAngle: toRad(arcOpt.endAngle)
      },
      style: {
        fill: null,
        stroke: '#12718E',
        strokeOpacity: 0.8,
        lineWidth: 2
      }
    });

    animateRotate(arc);
    zr.add(arc);

  });

  let circle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 50
    },
    style: {
      fill: gradient,
      fillOpacity: 0.5,
      stroke: "#009adb",
      lineWidth: 2,
      text: percentage + '%',
      fontSize: "20",
      textFill: "#009adb"
    }
  });

  addCircleToChart(chart, 60, 2, 180);
  addCircleToChart(chart, 60, 2, 360);
  zr.add(circle);
  drawPointer(chart);

  elements.circle = circle;
}


function drawPointer(chart) {
  const R = 50;
  const R1 = 2;
  for (let i = 0; i < 360; i += 10) {
    addCircleToChart(chart, R - 10, R1, i, false, '#0A7693');
  }
}

function update(percentage) {
  elements.circle.attr({
    style: {
      text: percentage + '%',
    }
  });
}



export default {
  draw,
  update
}
